<script setup lang="ts">
import { reactive, ref, h, onMounted, onUnmounted, nextTick, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router';
import { NCard, NButton, NBreadcrumb, NBreadcrumbItem, NGrid, NGridItem, NSpace, useDialog, NPopover } from 'naive-ui'
import { NDropdown, NFlex, NDrawer, NDrawerContent, NBadge, NSwitch, NInput, createDiscreteApi, NDescriptions, NDescriptionsItem } from 'naive-ui'
import SvgIcon from '@/components/SvgIcon.vue';
import { sseService } from "../assets/utils/sse";
import type { SSEChatParams } from "../assets/utils/sse";
import { setUrl } from "@/service/sseUrl";
import Papa from "papaparse";
import { APP_DEL, FORM_ADD, FOLDER_UPD } from "@/service/apis/from";
import { useCounterStore } from './../stores/counter'
const { message } = createDiscreteApi(["message"])
const dialog = useDialog()
const fileList: any = ref([]);
const dirList: any = ref([]);
const appFileList: any = ref([]);
const router = useRouter()
const appId = 'E68891E79A84E695B0E68DAEE58C85'
let currentDir = reactive([{
    name: '我的数据包',
    path: appId,
}])

onMounted(() => {
    sseServiceOpen()
})
onUnmounted(() => {
    sseService.disconnect()
})

function reconnect() {
    fileList.value = []
    dirList.value = []
    appFileList.value = []
    sseService.disconnect()
    sseServiceOpen()
}

/**
 * 根据currentDir 计算出SSE的url
 */
const initUrl = () => {
    let url = currentDir[0].path
    if (currentDir.length > 1) {
        url += '/'
        for (let i = 1; i < currentDir.length; i++) {
            url += `${currentDir[i].path}-`
        }
        url = url.slice(0, -1)
    }

    return url
}
//see 链接
function sseServiceOpen() {
    const url = initUrl()
    const onopen = () => {
        console.log("文件夹、文件列表sse连接成功", url)
    }
    console.log('尝试创建SSE', url)
    // 建立连接
    let sseChatParams: SSEChatParams = {
        onopen,
        url: setUrl(url),
        onmessage: (event: MessageEvent) => {
            // 收到消息
            console.log('收到消息', event.data);
            let fst = event.data.replace(/\\n/g, "\n")
            const ddf = Papa.parse(fst, { header: true, delimiter: ";", newline: "\n" })
            fileList.value = [...fileList.value, ...ddf.data]
            console.log('文件、文件夹列表', ddf.data, fileList)
            dirList.value = fileList.value.filter((item: any) => item.类型 === 'dir')
            appFileList.value = fileList.value.filter((item: any) => item.类型 !== 'dir')
        },
        finallyHandler: () => {
            console.log("finallyHandler操作")
        }
    };
    sseService.connect(sseChatParams)
}


/**
 * 头部标题图标设置
 * 头标下拉菜单设置
 */
const options_dataset = [
    { label: '新建文档', key: 'word' },
    { label: '新建表格', key: 'excel' },
    { label: '新建文件夹', key: 'folder' },
    { label: '关闭', key: 'close' },
]
const datasetSelect = (key: string) => {
    console.log(key)
    if (key === 'word') {
        router.push('word')
    }
    if (key === 'excel') {
        router.push('excel')
    }
    if (key === 'folder') {
        newFolder()
    }
    if (key === 'close') {
        handleClose()
    }
}
let datasetIcon = () => {
    return h(NFlex, () => [
        h(NDropdown, { trigger: "hover", size: "huge", showArrow: true, options: options_dataset, onSelect: datasetSelect }, () => h(NButton, { text: true, style: 'font-size: 24px' }, () => h(SvgIcon, { iconClass: 'wodeshujuji' }))),
        h(NBreadcrumb, { separator: '>' }, () =>
            currentDir.map((item, index) => h(NBreadcrumbItem, { onClick: () => clickBreadCrumbItem(item, index) }, () => h('div', { style: 'font-size :18px' }, item.name)))
        ),
    ])
}
const header_dataset = () => datasetIcon()
/**
 * end
 */

let newFolderNameInputValue = ref('新建文件夹')

const newFolder = () => {
    dirList.value = [...dirList.value, {
        "类型": "dir",
        "need_create": true
    }]
    newFolderNameInputValue.value = '新建文件夹'
}

const saveFolderByInputValue = () => {
    const path = currentDir.length > 1 ? currentDir.slice(1).map(item => item.name).join('/') + '/' + newFolderNameInputValue.value : newFolderNameInputValue.value
    const data = {
        类型: "文件夹",
        内容: {
            应用名称: '我的数据包',
            文件夹路径: path
        }
    }
    console.log('提交的数据', data, currentDir)

    FORM_ADD({ "params": JSON.stringify(data) }).then((res: any) => {
        if (res.stacode == 200) {
            message.success(res.message)
            reconnect()
        }
    }).catch((err: any) => {
        console.log('err', err);
    })
}

/**
* 关闭应用，返回路由上一页
*/
const handleClose = () => {
    router.go(-1)
}

const dirIconClick = (item: any) => {
    console.log(item, currentDir)
    console.log(currentDir.map((item) => h('div', { style: 'font-size :18px' }, item.name)))
    currentDir.push({
        name: item.文件名,
        path: item.缩写
    })
    reconnect()
}

const clickBreadCrumbItem = (item: any, index: number) => {
    console.log(item)
    // 截断currentDir  
    currentDir.splice(index + 1)
    reconnect()
}

let currentDisplayMode = ref('bigIcon')

const changeDisplayMode = () => {
    if (currentDisplayMode.value === 'list') {
        currentDisplayMode.value = 'bigIcon'

    } else {
        currentDisplayMode.value = 'list'
    }
}

let isOnDrag = false
let dragFile: any
let dropFolder: any
const onDragStart = (file: any) => {
    console.log('拖拽了：', file)
    dragFile = file
    isOnDrag = true
    showCloseButton.value = false
};

const onDragEnd = (file: any) => {
    console.log('拖拽松开了：', file)
    isOnDrag = false
    showCloseButton.value = false
};

const onDrop = (event: any, folder: any) => {
    console.log('放到了', folder)
    dropFolder = folder
    isOnDrag = false

    const currentPath = currentDir.length > 1 ? currentDir.slice(1).map(item => item.name).join('/') : ''
    const data = {
        "类型": "数据移动",
        "内容": {
            "应用名称": "我的数据包",
            "文件名": dragFile.文件名,
            "当前路径": currentPath,
            "目标路径": currentPath + '/' + folder.文件名,
        }
    }
    FOLDER_UPD({ "params": JSON.stringify(data) }).then((res: any) => {
        if (res.stacode == 200) {
            message.success(res.message)
            reconnect()
        }
    }).catch((err: any) => {
        console.log('err', err);
    })
};

let isLongPressing = false;
let longPressTimer: any
let showCloseButton = ref(false)

const handleMouseDown = () => {
    console.log('鼠标按下')
    // 阻止默认行为，比如选择文本  
    isLongPressing = false;
    // 设置长按定时器  
    longPressTimer = setTimeout(() => {
        if (isOnDrag) {
            return
        }
        isLongPressing = true;
        handleLongPress();
    }, 1200);
    setTimeout(() => {
        if (isOnDrag) {
            clearTimeout(longPressTimer);
        }
    }, 500);
}
const handleMouseUp = () => {
    console.log('鼠标抬起')
    // 清除长按定时器  
    clearTimeout(longPressTimer);
    // 重置长按状态  
    isLongPressing = false;
    // 如果需要，可以在这里处理普通的点击事件（但要确保与双击逻辑不冲突）  
    // 注意：在这个示例中，我们不处理普通的点击事件，因为它可能与双击冲突。  
    // 如果你需要处理点击事件，请确保在 handleClick 方法中进行适当的检查。  
}
const handleLongPress = () => {
    // 在这里处理长按逻辑
    if (!isOnDrag) {
        console.log('这是一次长按')
        showCloseButton.value = !showCloseButton.value
    }
}


const delFile = (item: any) => {
    console.log('准备删除', item)
    const currentIdPath = currentDir.length > 1 ? currentDir.slice(1).map(item => item.path + '/') : ''
    dialog.warning({
        title: '删除',
        content: `确定删除 ${item.文件名} ?`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            let data = {
                "应用名称": appId, // 必填
                "应用类型": "数据", // 必填
                "文件类型": item['类型'],
                "文件名": currentIdPath + item['缩写'],
            }

            APP_DEL({ "params": JSON.stringify(data) }).then((res: any) => {
                if (res.stacode == 200) {
                    message.success(res.message)
                    reconnect()
                }
                else {
                    message.error(res.message)
                }
            }).catch((err: any) => {
                console.log('err', err);
            })
        }
    })
}

const itemDoubleClick = (val: any) => {
    console.log('文件信息', val);
    if (val['文件格式'] === 'docx') {
        const info = {
            appId,
            appName: '我的数据包',
            type: 'word',
            fileId: val['缩写'],
            fileName: val['文件名'],
            pathUrl: initUrl()
        }
        useCounterStore().setOpenFileInfo(info)
        router.push('word');
    } else if (val['文件格式'] === 'xlsx') {
        const info = {
            appId,
            appName: '我的数据包',
            type: 'excel',
            fileId: val['缩写'],
            fileName: val['文件名'],
            pathUrl: initUrl()
        }
        useCounterStore().setOpenFileInfo(info)
        router.push('excel');
    }
}

/**
 * 右键菜单
 */
const showDropdown = ref(false)
const x = ref(0)
const y = ref(0)
const options: any = ref([])
const currentRightClickItem: any = ref(null)
const handleContextMenu = (e: MouseEvent, item?:any) => {
    console.log('右键菜单', e, item)
    e.preventDefault()// 阻止默认上下文菜单  
    e.stopPropagation(); // 阻止事件冒泡到父层 

    options.value = [
        { label: '新建文档', key: 'word' },
        { label: '新建表格', key: 'excel' },
        { label: '新建文件夹', key: '文件夹' },
        { label: '刷新', key: '刷新' },
        { label: '删除数据文件', key: '删除' },
        { label: '关闭 我的数据包', key: '关闭' },
    ]

    if (item) {
        options.value = [
            { label: '共享', key: '共享' },
            { type: 'divider', key: 'd1' },
            { label: '新建文档', key: 'word' },
            { label: '新建表格', key: 'excel' },
            { label: '新建文件夹', key: '文件夹' },
            { label: '删除数据文件', key: '删除' },
            { type: 'divider', key: 'd1' },
            { label: '属性', key: '属性' }
        ]
        currentRightClickItem.value = item
    }

    showDropdown.value = false
    nextTick().then(() => {
        showDropdown.value = true
        x.value = e.clientX
        y.value = e.clientY
    })
}
const onClickoutside = () => {

    showDropdown.value = false
}
const handleSelect = (key: string | number) => {
    showDropdown.value = false
    switch (key) {
        case 'word':
            router.push('word')
            break;
        case 'excel':
            router.push('excel')
            break;
        case '文件夹':
            newFolder()
            break;
        case '删除':
            handleLongPress()
            break;
        case '刷新':
            reconnect()
            break;
        case '关闭':
            handleClose()
            break;
        case '属性':
            handleShowPropertyDrawer()
            break;
    }
}

const showPropertyDrawer = ref(false)
const handleShowPropertyDrawer = () => {
    showPropertyDrawer.value = true
}



/**
 * 获取窗口宽度大小，以判定grid布局的显示的solt数量
 */
const windowWidth = ref<number>(window.innerWidth)
const updateWindowWidth = () => {
    windowWidth.value = window.innerWidth
}
onMounted(() => {
    window.addEventListener('resize', () => { updateWindowWidth() })
})

onBeforeUnmount(() => {
    window.removeEventListener('resize', () => { updateWindowWidth() })
})
</script>
<template>
    <n-card :title="header_dataset" style="height: 100%;" content-class="scrollableContent" closable
        @close="handleClose" @contextmenu="handleContextMenu">
        <template #header-extra>
            <slot name="header-extra"></slot>
            <n-switch @update:value="changeDisplayMode" style="padding-right: 10px;">
                <template #unchecked>图标</template>
                <template #checked>列表</template>
            </n-switch>
        </template>
        <template #default>
            <slot></slot>
            <n-flex id="drawer-set" vertical>
                <n-flex>
                    <div style="position: relative; display: flex; justify-content: center;">
                        <NGrid :x-gap="3" :y-gap="3" :cols="windowWidth > 1024 ? 6 : 2"
                            v-if="currentDisplayMode === 'list'" style="padding: 5px;">
                            <NGridItem class="hoverItem" v-for="item in dirList"
                                style="border-bottom: 1px #ddd solid; padding: 10px;" @dblclick="datasetSelect(item.类型)"
                                @dragover.prevent @drop="onDrop($event, item)">
                                <NSpace @dblclick="dirIconClick(item)">
                                    <n-badge :show="item.标记 !== undefined && item.标记 > 0" :value="Number(item.标记)" :max="9">
                                        <SvgIcon iconClass="wenjiangui" style="width:25px; height:25px; opacity: 0.8;">
                                        </SvgIcon>
                                    </n-badge>
                                    <NInput v-if="item.need_create" v-model:value="newFolderNameInputValue" size="small"
                                        :on-blur="saveFolderByInputValue" maxlength="10"></NInput>
                                    <n-popover v-else-if="item['文件名'].length > 12" placement="bottom" trigger="hover">
                                        <template #trigger>
                                            <div style="width: 180px;white-space: nowrap; overflow: hidden;  text-overflow: ellipsis;">
                                                {{ item['文件名'] }}</div>
                                        </template>
                                        <span>{{ item['文件名'] }}</span>
                                    </n-popover>
                                    <div v-else> {{ item['文件名'] }}</div>
                                    <div style="color: lightgray;">{{ item.创建时间 }}</div>
                                </NSpace>
                            </NGridItem>

                            <NGridItem class="hoverItem" v-for="item in appFileList"
                                style="border-bottom: 1px #ddd solid; padding: 10px;" @dblclick="itemDoubleClick(item)"
                                draggable="true" @dragstart="onDragStart(item)" @dragend="onDragEnd(item)"
                                @mousedown="handleMouseDown()" @mouseup="handleMouseUp()" @mouseleave="handleMouseUp()"
                                @contextmenu.prevent="handleContextMenu($event, item)">
                                <NSpace>
                                    <SvgIcon v-if="item.文件格式 === 'docx'" iconClass="word2"
                                        style="width:25px; height:25px; opacity: 0.8;"></SvgIcon>
                                    <SvgIcon v-else-if="item.文件格式 === 'xlsx'" iconClass="excel4"
                                        style="width:25px; height:25px; opacity: 0.8;"></SvgIcon>
                                    <n-popover v-if="item['文件名'].length > 12" placement="bottom" trigger="hover">
                                        <template #trigger>
                                            <div style="width: 180px;white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                                                {{ item['文件名'] }}</div>
                                        </template>
                                        <span>{{ item['文件名'] }}</span>
                                    </n-popover>
                                    <div v-else> {{ item['文件名'] }}</div>
                                    <div style="color: lightgray;">{{ item.创建时间 }}</div>
                                    <SvgIcon iconClass="guanbi3" style="width:20px; height:20px; "
                                        v-if="showCloseButton" @click="showCloseButton ? delFile(item) : undefined">
                                    </SvgIcon>

                                </NSpace>
                            </NGridItem>
                        </NGrid>
                        <NGrid :x-gap="3" :y-gap="3"
                            :cols="windowWidth > 1920 ? 24 : windowWidth > 1280 ? 16 : windowWidth > 1024 ? 12 : 8"
                            v-if="currentDisplayMode !== 'list'">
                            <NGridItem :id="item.文件名" v-for=" item in dirList" style="text-align: center; padding: 10px"
                                @dragover.prevent @drop="onDrop($event, item)" @dblclick="dirIconClick(item)">
                                <span>
                                    <n-badge :show="item.标记 !== undefined && item.标记 > 0" :value="Number(item.标记)"
                                        :max="99">
                                        <!-- <img width="60px" height="60px"> -->
                                        <SvgIcon iconClass="wenjiangui" style="width:60px; height:60px; opacity: 0.6;">
                                        </SvgIcon>
                                    </n-badge>
                                    <NInput v-if="item.need_create" v-model:value="newFolderNameInputValue" size="small"
                                        :on-blur="saveFolderByInputValue" maxlength="10"></NInput>
                                    <n-popover v-else-if="item['文件名'].length > 6" placement="bottom" trigger="hover">
                                        <template #trigger>
                                            <div
                                                style="white-space: nowrap; overflow: hidden;  text-overflow: ellipsis;">
                                                {{ item['文件名'] }}</div>
                                        </template>
                                        <span>{{ item['文件名'] }}</span>
                                    </n-popover>
                                    <div v-else> {{ item['文件名'] }}</div>
                                </span>
                            </NGridItem>

                            <NGridItem v-for="item in appFileList" style="padding: 10px; text-align: center; cursor: pointer;"
                                @dblclick="itemDoubleClick(item)" draggable="true" @dragstart="onDragStart(item)"
                                @dragend="onDragEnd(item)" @mousedown="handleMouseDown()" @mouseup="handleMouseUp()"
                                @mouseleave="handleMouseUp()" @contextmenu.prevent="handleContextMenu($event, item)">
                                <span>
                                    <n-badge value="x" color="lightGray" :show="showCloseButton"
                                        @click="showCloseButton ? delFile(item) : undefined">
                                        <SvgIcon v-if="item.文件格式 === 'docx'" iconClass="word2"
                                            @click.stop="console.log('点击图标，拦截事件穿透')"
                                            style="text-align: center; width:60px; height:60px; opacity: 0.8;">
                                        </SvgIcon>
                                        <SvgIcon v-else-if="item.文件格式 === 'xlsx'" iconClass="excel4"
                                            @click.stop="console.log('点击图标，拦截事件穿透')"
                                            style="width:60px; height:60px; opacity: 0.8;"></SvgIcon>
                                    </n-badge>
                                    <n-popover v-if="item['文件名'].length > 6" placement="bottom" trigger="hover">
                                        <template #trigger>
                                            <div
                                                style="white-space: nowrap; overflow: hidden;  text-overflow: ellipsis;">
                                                {{ item['文件名'] }}</div>
                                        </template>
                                        <span>{{ item['文件名'] }}</span>
                                    </n-popover>
                                    <div v-else> {{ item['文件名'] }}</div>
                                </span>
                            </NGridItem>

                        </NGrid>
                    </div>
                </n-flex>
            </n-flex>
            <n-drawer v-model:show="showPropertyDrawer" :width="300" show-mask="transparent" placement="right":block-scroll="false"  to="#drawer-set">
                <n-drawer-content title="属性" closable>
                    <n-descriptions label-placement="top" :column="1" :title="currentRightClickItem['文件名'] + '.' + currentRightClickItem['文件格式']">
                        <n-descriptions-item label="创建时间">
                            {{currentRightClickItem['创建时间']}}
                        </n-descriptions-item>
                        <n-descriptions-item label="类型"> 
                            {{currentRightClickItem['类型']}}
                        </n-descriptions-item>
                    </n-descriptions>
                </n-drawer-content>
            </n-drawer>

            <n-dropdown placement="bottom-start" trigger="manual" :x="x" :y="y" :options="options" :show="showDropdown"
                :on-clickoutside="onClickoutside" @select="handleSelect" />
        </template>

        <template #footer>
            <slot name="footer"></slot>
        </template>

    </n-card>
</template>
<style>
.hoverItem:hover {
    border: 1px solid #575757;
    background-color: #AAAAAA;
    opacity: 0.7;
    color: white;
}

.scrollableContent {
    overflow-y: auto;
}

/* 滚动条轨道 */
.scrollableContent::-webkit-scrollbar-track {
    background: #FFFFFF;
    /* 轨道颜色 */
}

.scrollableContent::-webkit-scrollbar-thumb {
    background: #ddd;
    /* 滑块颜色 */
    border-radius: 4px;
    /* 滑块圆角 */
}

/* 整个滚动条 */
.scrollableContent::-webkit-scrollbar {
    /* 滚动条的宽度 */
    width: 8px;
}
</style>